package edu.sjsu.itack.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import edu.sjsu.itack.util.ApplicationProperties;
import edu.sjsu.itack.util.ITackException;


public class ConnectionFactory {

	/**
	 * Connection parameters
	 */
	private String connectionUrl; 
	private String user; 
	private String password;
	private String driver; 

	private static ConnectionFactory factory = null;

	public static ConnectionFactory getInstance() {
		if (factory == null)
			factory = new ConnectionFactory();
		return factory;
	}
	
	/**
	 * Private constructor to limit the instantiation to class itself
	 */
	private ConnectionFactory(){
		init();
		try{
			Class.forName(driver);
		}
		catch (ClassNotFoundException e){
			e.printStackTrace(System.out);
		}
	}

	/**
	 * Initialize all the db connection parameters from the properties
	 */
	private void init(){
		driver = ApplicationProperties.getProperty("driver");
		connectionUrl = ApplicationProperties.getProperty("url");
		user = ApplicationProperties.getProperty("user");
		password = ApplicationProperties.getProperty("password");
	}

	/**
	 * Gets the db connection
	 * @return
	 * @throws ITackException
	 */
	
	public Connection getConnection() throws ITackException{
		Connection con = null;
		try {
			con = DriverManager.getConnection(connectionUrl,user,password);
		} catch (SQLException e) {
			throw new ITackException(null, e);
		}
		return con;
	}

	/**
	 * Closes the db connection
	 * @param con
	 * @throws ITackException
	 */
	public void closeConnection(Connection con) throws ITackException{
		if (con == null)
			return;
		
		try {
			con.close();
		} catch (SQLException e) {
			throw new ITackException(null, e);
		}
	}
}
